处世如大梦,悟者能有几

— 宋·李纲

作者:Pluto
更新时间:2026-04-15

1. 安装

1.1 RedHat系列安装

sudo dnf install fail2ban 
或 
sudo yum install fail2ban

1.2 Debian系列安装

sudo apt update && sudo apt install fail2ban

1.3 启动和设置开机自启

# 启动 Fail2ban 服务
sudo systemctl start fail2ban

# 设置开机自启
sudo systemctl enable fail2ban

# 查看服务状态
sudo systemctl status fail2ban

2. 配置 Fail2ban

Fail2ban 的主配置文件是 `/etc/fail2ban/jail.conf`。**但强烈建议不要直接修改它**,因为软件更新时可能会覆盖这个文件。正确的做法是创建一个本地配置文件 `/etc/fail2ban/jail.local`,它会覆盖 `jail.conf` 中的相应设置。

2.1 创建本地配置文件

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

2.2 编辑 jail.local

sudo nano /etc/fail2ban/jail.local  
# 或使用 vi/vim 
sudo vim /etc/fail2ban/jail.local

2.3 SSH Jail (最重要)

:::info Debian/Ubuntu 使用的日志文件通常是 /var/log/auth.logRedHat 系列使用的日志文件通常是 /var/log/secure

:::

[sshd]
# 启用 SSH 保护
enabled = true
port    = ssh
# 默认情况下,filter 指向 filter.d/sshd.conf
filter  = sshd
# RedHat 系列通常是 /var/log/secure;Debian/Ubuntu 系列通常是 /var/log/auth.log
logpath = %(sshd_log)s
maxretry = 3   # 可以设置得更严格,例如 3 次
findtime = 10m  # 意思是5分钟内检查尝试的次数
bantime  = 24d # 封禁的时间: s 表示秒, h 表示小时, d 表示天

2.4 其他常见 Jail 示例

# Apache 基础认证失败保护
[apache-auth]
enabled = true
port    = http,https
filter  = apache-auth
logpath = /var/log/apache2/error.log  ; 或 /var/log/httpd/error_log
maxretry = 6
findtime = 5m  ; 意思是5分钟内检查尝试的次数
bantime  = 24d ; 封禁的时间: s 表示秒, h 表示小时, d 表示天

# Nginx HTTP 认证失败保护 (需要相应的 filter.d/nginx-http-auth.conf)
[nginx-http-auth]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/error.log
maxretry = 6
findtime = 5m  ; 意思是5分钟内检查尝试的次数
bantime  = 24d ; 封禁的时间: s 表示秒, h 表示小时, d 表示天

3. 启动与后续设置

3.1 启动并设置开机自动启动Fail2ban

sudo systemctl start fail2ban
sudo systemctl enable fail2ban

3.2 测试和验证配置

3.2.1 查看总状态

sudo fail2ban-client status
 
# 输出示例
 Status
|- Number of jail:      2
`- Jail list:   sshd, nginx-http-auth

3.2.2 查看特定 Jail 状态

检查Fail2ban是否正常运行,并查看已屏蔽的IP地址列表(如果有的话)

sudo fail2ban-client status sshd

手动解封 IP 地址

sudo fail2ban-client unban 111.222.333.444